Schedule user logged in#470
Conversation
move detectSchedulePermission to the handler which broke many tests using the mock handler
WalkthroughThis pull request spans multiple files across the project. It updates GitHub Actions workflows for broken link checking, modifies configuration files (e.g. Makefile, .gitignore, codecov.yml), and improves scheduling functionality. In the schedule subsystem, permission handling is refactored by switching from string‐based permissions to a new integer-based type, with corresponding updates to handlers, mocks, tests, and documentation. In addition, new fields enabling per-user scheduling (e.g. a new User field in the systemd service generator) have been introduced alongside enhancements to the darwin and user packages. Changes
Sequence Diagram(s)sequenceDiagram
participant U as User
participant HS as HandlerSystemd
participant SG as SystemdGenerator
participant OS as OS Environment
U->>HS: Request job creation with specific permission
HS->>HS: Call DetectSchedulePermission(permission)
HS->>SG: Invoke Generate(config with User field)
SG->>OS: Retrieve user info (via user.Current or os.UserHomeDir)
OS-->>SG: Return home directory and environment details
SG-->>HS: Return generated service file
HS->>U: Confirm scheduled job creation
Assessment against linked issues
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## master #470 +/- ##
==========================================
+ Coverage 79.36% 79.46% +0.10%
==========================================
Files 131 132 +1
Lines 12959 13169 +210
==========================================
+ Hits 10284 10464 +180
- Misses 2269 2292 +23
- Partials 406 413 +7
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (14)
crond/entry.go (1)
36-40:WithUserMethod Implementation:
TheWithUsermethod appropriately trims the input value before assigning it to theuserfield. This helps prevent issues with extraneous whitespace. Consider if additional validation is required for special cases (e.g. values like"*"or"-").user/user.go (1)
1-9: New User Package andUserStruct:
A new packageuserhas been introduced, featuring theUserstruct with fields for UID, GID, Username, HomeDir, and SudoRoot. The implementation is straightforward; however, adding documentation comments for each field would enhance clarity and maintainability. Additionally, consider implementing unit tests to verify the behaviour of any future methods that utilise this struct.codecov.yml (1)
15-15: Clarification on Ignored Coverage File.
The new entry- user/user_systemd.gois now excluded from code coverage. Please confirm that this file’s omission is intentional—if it contains user permission handling that might be critical (especially with the recent changes regarding user permissions), ensure that its functionality is sufficiently tested elsewhere or reconsider ignoring it..gitignore (1)
6-10: New Ignore Patterns for Log and Crontab Files.
The inclusion of/examples/*-log.txtand/crontabprevents tracking of generated log files and the crontab file. Please verify that these patterns accurately capture the intended files and that no essential files are being unintentionally ignored.examples/dev.yaml (1)
136-144: Commented out forget and copy sectionsI notice these sections have been commented out rather than removed. Consider whether these should be completely removed or if they're intended to be re-enabled later.
examples/linux.yaml (1)
105-105: Fix indentation in schedule sectionThe indentation for the
atproperty is incorrect according to YAML standards. It should be indented with 12 spaces to match the parent structure.- at: "*:15,20,25" + at: "*:15,20,25"🧰 Tools
🪛 YAMLlint (1.35.1)
[warning] 105-105: wrong indentation: expected 12 but found 10
(indentation)
schedule/schedules_test.go (1)
73-73: Consider using a more flexible approach for systemd-analyze path.Using the absolute path
/usr/bin/systemd-analyzemakes the test more brittle as it will fail if the binary is installed in a different location. On some systems, it might be in/bin/systemd-analyzeor elsewhere.Consider one of these alternatives:
-_, err := exec.LookPath("/usr/bin/systemd-analyze") +_, err := exec.LookPath("systemd-analyze")Or if you need to check specific paths:
-_, err := exec.LookPath("/usr/bin/systemd-analyze") +_, err := findSystemdAnalyze()With a helper function like:
func findSystemdAnalyze() (string, error) { // Try common locations for _, path := range []string{"/usr/bin/systemd-analyze", "/bin/systemd-analyze"} { if _, err := os.Stat(path); err == nil { return path, nil } } // Fall back to PATH lookup return exec.LookPath("systemd-analyze") }docs/content/schedules/systemd.md (1)
32-37: Improved readability with bullet points, but contains duplicated wordThe restructured section using bullet points improves readability by clearly separating the steps. However, there's a duplicated "Run" in line 36-37.
Correct the duplicated word by applying this change:
- Run `systemctl enable` - Run `systemctl start` + Run `systemctl enable` + Run `systemctl start`🧰 Tools
🪛 LanguageTool
[duplication] ~36-~36: Possible typo: you repeated a word.
Context: ...edule-permissionis set tosystem) - Runsystemctl enable- Runsystemctl start` ## Priority and CPU ...(ENGLISH_WORD_REPEAT_RULE)
docs/content/schedules/launchd.md (1)
10-10: Consider standardising the naming convention.
Your text mentionsuser_logged-on. In the codebase, we often seePermissionUserLoggedOn. For consistency, you might prefer an underscore instead of a dash:- A user agent is generated when you set `schedule-permission` to `user` or `user_logged-on`. + A user agent is generated when you set `schedule-permission` to `user` or `user_logged_on`.schedule/handler_windows.go (1)
74-74: Thepermissionparameter is not consumed here.
Consider removing it from the signature or using it if necessary for future logic.docs/content/schedules/_index.md (1)
18-18: Potential grammar improvement.
“otherwise” is used as an adverb; consider rewording to avoid confusion, for example:On Unix systems (excluding macOS), resticprofile uses systemd if available. If it isn’t available, it falls back to crond.
🧰 Tools
🪛 LanguageTool
[typographical] ~18-~18: The word “otherwise” is an adverb that can’t be used like a conjunction, and therefore needs to be separated from the sentence.
Context: ...cOS), resticprofile uses systemd if available, otherwise it falls back to crond. See [refer...(THUS_SENTENCE)
schedule/handler_darwin_test.go (1)
171-245: New TestParsePrint function.
Parses launchctl output for correctness. Consider adding a scenario for empty or corrupt output if deeper coverage is required.schedule/handler_darwin.go (2)
243-261: DetectSchedulePermission fallback logic.
Providing a sensible default permission based on whether the process is running as root strengthens reliability. You might consider clarifying or documenting any subtle differences between "logged in" and "logged on" usage to avoid confusion.
326-351: Creating plist files and ensuring correct ownership.
The creation process withMkdirAllat0o700is secure. The additional logic handlingsudoRootusage and applying the correctChownmaintains expected file permissions. Consider validating the final file mode if adherence to stricter security is desired.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (67)
.github/workflows/doc.yml(1 hunks).github/workflows/release-doc.yml(1 hunks).gitignore(1 hunks)Makefile(2 hunks)codecov.yml(1 hunks)commands_schedule_test.go(2 hunks)constants/value.go(1 hunks)crond/crontab.go(2 hunks)crond/crontab_test.go(1 hunks)crond/entry.go(1 hunks)crond/entry_test.go(1 hunks)crond/io.go(1 hunks)crond/parse_event.go(1 hunks)crond/parse_event_test.go(1 hunks)darwin/calendar_interval.go(3 hunks)darwin/calendar_interval_test.go(1 hunks)darwin/launchd.go(1 hunks)darwin/process_type.go(1 hunks)darwin/process_type_test.go(1 hunks)darwin/session_type.go(1 hunks)darwin/session_type_test.go(1 hunks)darwin/tree.go(1 hunks)darwin/tree_test.go(1 hunks)docs/content/schedules/_index.md(2 hunks)docs/content/schedules/commands.md(1 hunks)docs/content/schedules/configuration.md(3 hunks)docs/content/schedules/cron.md(1 hunks)docs/content/schedules/launchd.md(1 hunks)docs/content/schedules/systemd.md(5 hunks)examples/dev.yaml(3 hunks)examples/linux.yaml(2 hunks)examples/sample.service(2 hunks)schedule/calendar_interval_test.go(0 hunks)schedule/config.go(1 hunks)schedule/config_test.go(1 hunks)schedule/handler.go(2 hunks)schedule/handler_crond.go(7 hunks)schedule/handler_crond_test.go(5 hunks)schedule/handler_darwin.go(15 hunks)schedule/handler_darwin_test.go(7 hunks)schedule/handler_systemd.go(14 hunks)schedule/handler_systemd_test.go(4 hunks)schedule/handler_windows.go(4 hunks)schedule/handler_windows_test.go(1 hunks)schedule/job.go(5 hunks)schedule/job_test.go(5 hunks)schedule/mocks/Handler.go(8 hunks)schedule/permission.go(1 hunks)schedule/permission_test.go(0 hunks)schedule/permission_unix.go(0 hunks)schedule/permission_windows.go(0 hunks)schedule/schedules.go(2 hunks)schedule/schedules_test.go(1 hunks)schedule/spaced_title.go(0 hunks)schedule/spaced_title_test.go(0 hunks)schedule_jobs.go(1 hunks)schedule_jobs_test.go(14 hunks)schtasks/taskscheduler.go(1 hunks)systemd/generate.go(7 hunks)systemd/generate_test.go(1 hunks)systemd/read.go(1 hunks)systemd/read_test.go(2 hunks)user/user.go(1 hunks)user/user_other.go(1 hunks)user/user_systemd.go(1 hunks)user/user_test.go(1 hunks)user/user_windows.go(1 hunks)
💤 Files with no reviewable changes (6)
- schedule/spaced_title.go
- schedule/calendar_interval_test.go
- schedule/spaced_title_test.go
- schedule/permission_windows.go
- schedule/permission_test.go
- schedule/permission_unix.go
🧰 Additional context used
🧬 Code Definitions (23)
user/user_test.go (2)
user/user_other.go (1)
Current(11-39)user/user_windows.go (1)
Current(9-23)
darwin/session_type_test.go (1)
darwin/session_type.go (1)
NewSessionType(17-32)
systemd/generate_test.go (3)
systemd/generate.go (5)
GetSystemDir(256-258)Generate(121-222)Config(94-114)UnitType(65-65)SystemUnit(70-70)config/config.go (1)
Config(28-48)user/user.go (1)
User(3-9)
user/user_windows.go (2)
user/user_other.go (1)
Current(11-39)user/user.go (1)
User(3-9)
darwin/launchd.go (3)
darwin/calendar_interval.go (1)
CalendarInterval(23-23)darwin/process_type.go (1)
ProcessType(7-7)darwin/session_type.go (1)
SessionType(7-7)
systemd/generate.go (3)
user/user.go (1)
User(3-9)user/user_other.go (1)
Current(11-39)user/user_windows.go (1)
Current(9-23)
schedule/handler_windows_test.go (4)
schedule/handler.go (1)
NewHandler(44-49)schedule/scheduler_config.go (1)
SchedulerWindows(32-32)schedule/handler_windows.go (1)
HandlerWindows(16-18)constants/global.go (1)
SchedulerWindows(12-12)
darwin/calendar_interval_test.go (1)
darwin/calendar_interval.go (2)
CalendarInterval(23-23)ParseCalendarIntervals(119-140)
user/user_other.go (2)
user/user_windows.go (1)
Current(9-23)user/user.go (1)
User(3-9)
schedule/handler.go (2)
schedule/permission.go (1)
Permission(7-7)schtasks/permission.go (1)
Permission(13-13)
systemd/read.go (1)
user/user.go (1)
User(3-9)
schedule/handler_crond_test.go (5)
schedule/permission.go (5)
Permission(7-7)PermissionFromConfig(16-30)PermissionUserLoggedOn(13-13)PermissionUserBackground(12-12)PermissionSystem(11-11)schedule/handler_crond.go (1)
HandlerCrond(22-25)systemd/generate.go (1)
Config(94-114)schedule/config.go (1)
Config(10-27)schedule/handler.go (1)
NewHandler(44-49)
darwin/process_type.go (1)
constants/value.go (2)
SchedulePriorityBackground(11-11)SchedulePriorityStandard(12-12)
systemd/read_test.go (3)
systemd/generate.go (3)
Config(94-114)UnitType(65-65)SystemUnit(70-70)schedule/config.go (1)
Config(10-27)user/user.go (1)
User(3-9)
schedule/job.go (1)
schedule/permission.go (2)
PermissionFromConfig(16-30)Permission(7-7)
darwin/session_type.go (1)
constants/value.go (4)
SchedulePermissionSystem(6-6)SchedulePermissionUser(7-7)SchedulePermissionUserLoggedOn(8-8)SchedulePermissionUserLoggedIn(9-9)
schedule/handler_windows.go (3)
schedule/config.go (1)
Config(10-27)schedule/permission.go (5)
Permission(7-7)PermissionUserBackground(12-12)PermissionUserLoggedOn(13-13)PermissionAuto(10-10)PermissionSystem(11-11)schtasks/permission.go (3)
Permission(13-13)SystemAccount(18-18)UserAccount(17-17)
crond/crontab.go (1)
user/user_other.go (1)
Current(11-39)
schedule/mocks/Handler.go (2)
schedule/handler.go (1)
Handler(12-29)schedule/permission.go (1)
Permission(7-7)
schedule/permission.go (1)
constants/value.go (5)
SchedulePermissionSystem(6-6)SchedulePermissionUser(7-7)SchedulePermissionUserLoggedIn(9-9)SchedulePermissionUserLoggedOn(8-8)SchedulePermissionAuto(5-5)
schedule/handler_systemd.go (4)
systemd/generate.go (2)
Config(94-114)UnitType(65-65)schedule/config.go (1)
Config(10-27)schedule/permission.go (5)
Permission(7-7)PermissionFromConfig(16-30)PermissionSystem(11-11)PermissionUserBackground(12-12)PermissionUserLoggedOn(13-13)schedule/handler.go (1)
Handler(12-29)
schedule/handler_darwin_test.go (7)
darwin/calendar_interval.go (1)
GetCalendarIntervalsFromSchedules(67-73)darwin/launchd.go (1)
LaunchdJob(7-100)constants/value.go (1)
SchedulePermissionUserLoggedOn(8-8)schedule/handler.go (1)
NewHandler(44-49)schedule/scheduler_config.go (1)
SchedulerLaunchd(37-37)constants/global.go (1)
SchedulerLaunchd(11-11)schedule/handler_darwin.go (1)
HandlerLaunchd(47-50)
schedule/handler_darwin.go (8)
schedule/config.go (1)
Config(10-27)schedule/permission.go (5)
Permission(7-7)PermissionFromConfig(16-30)PermissionSystem(11-11)PermissionUserBackground(12-12)PermissionUserLoggedOn(13-13)schedule/errors.go (1)
ErrScheduledJobNotFound(7-7)darwin/launchd.go (1)
LaunchdJob(7-100)darwin/calendar_interval.go (1)
GetCalendarIntervalsFromSchedules(67-73)darwin/process_type.go (2)
ProcessType(7-7)NewProcessType(14-25)darwin/session_type.go (1)
NewSessionType(17-32)user/user.go (1)
User(3-9)
🪛 YAMLlint (1.35.1)
examples/linux.yaml
[warning] 105-105: wrong indentation: expected 12 but found 10
(indentation)
🪛 LanguageTool
docs/content/schedules/configuration.md
[uncategorized] ~76-~76: Loose punctuation mark.
Context: ...user, or user_logged_on: * system: Access system or protected files. Run r...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~78-~78: Loose punctuation mark.
Context: ...levated permissions if needed. * user: Run the backup using current user permi...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...password on Windows. * user_logged_on: Not for crond - Provides the same p...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~99-~99: Loose punctuation mark.
Context: ...-waitis "0" or not specified. -fail`: Any lock failure immediately aborts the...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~100-~100: Loose punctuation mark.
Context: ...ediately aborts the schedule. - ignore: Skips resticprofile locks. Restic locks...
(UNLIKELY_OPENING_PUNCTUATION)
[style] ~109-~109: To form a complete sentence, be sure to include a subject.
Context: ...lt. ### schedule-log schedule-log` can be used in two ways: - Redirect all out...
(MISSING_IT_THERE)
[uncategorized] ~120-~120: Loose punctuation mark.
Context: ...s unnoticed while you work. - standard: The process gets the same priority as o...
(UNLIKELY_OPENING_PUNCTUATION)
[typographical] ~135-~135: Two consecutive dots
Context: ... , to separate multiple entries - Use .. for a range Limitations: - The di...
(DOUBLE_PUNCTUATION)
docs/content/schedules/systemd.md
[duplication] ~36-~36: Possible typo: you repeated a word.
Context: ...edule-permissionis set tosystem) - Run systemctl enable- Runsystemctl start` ## Priority and CPU ...
(ENGLISH_WORD_REPEAT_RULE)
docs/content/schedules/_index.md
[typographical] ~18-~18: The word “otherwise” is an adverb that can’t be used like a conjunction, and therefore needs to be separated from the sentence.
Context: ...cOS), resticprofile uses systemd if available, otherwise it falls back to crond. See [refer...
(THUS_SENTENCE)
🪛 markdownlint-cli2 (0.17.2)
docs/content/schedules/configuration.md
90-90: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
91-91: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
92-92: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
98-98: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
99-99: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
100-100: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
110-110: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
111-111: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
119-119: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
120-120: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
129-129: Fenced code blocks should have a language specified
null
(MD040, fenced-code-language)
133-133: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
134-134: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
135-135: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
138-138: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
139-139: Unordered list style
Expected: asterisk; Actual: dash
(MD004, ul-style)
143-143: Fenced code blocks should have a language specified
null
(MD040, fenced-code-language)
🔇 Additional comments (235)
darwin/tree.go (1)
3-3: Package Name Update:
The package name has been updated fromscheduletodarwinas expected. This change correctly aligns the file with the new namespace, but please ensure that all import statements across the codebase have been updated accordingly.darwin/tree_test.go (1)
3-3: Package Name Revision in Test File:
The package declaration has been modified todarwinin the test file. This is consistent with the changes applied to the main file and should ensure that tests run under the correct namespace.crond/parse_event.go (1)
1-2: Added Build Constraint:
The build constraint//go:build !windowshas been added at the top of the file to exclude Windows builds. This is appropriate given the current project requirements.crond/entry.go (3)
1-2: Added Build Constraint:
The file now starts with the build constraint//go:build !windows, ensuring this file is excluded from Windows builds.
14-22: NewuserField in Entry Struct:
A new fielduserhas been introduced in theEntrystruct. This addition is central to handling user permissions more accurately. Please ensure that downstream code (including tests) correctly utilises this new field, as further related functionality seems to be implemented.
71-75: Conditional Formatting inStringMethod:
TheStringmethod now conditionally includes theuserfield based on theHasUser()andSkipUser()predicates. This is a good approach for controlling output depending on the user’s state. Ensure that the handling of special values (such as"*"indicating a needed user and"-"for skipping) is thoroughly tested and clearly documented.crond/io.go (1)
1-2: Build Constraint Addition Validated.
The added//go:build !windowsdirective clearly indicates that this file is only relevant for non-Windows builds. This is well aligned with platform-specific requirements and ensures that no Windows-specific build issues occur.schtasks/taskscheduler.go (1)
50-51: Enhanced Error Message Clarity.
The updated error message
return fmt.Errorf("cannot delete existing task to replace it: %w", err)
provides a clearer description when deletion of an existing task fails. Ensure that this phrasing remains consistent with similar error messages elsewhere in the codebase.crond/crontab_test.go (3)
1-2: Appropriate Build Constraint in Test File.
Adding//go:build !windowsat the top ensures that these tests run only in non-Windows environments, aligning test execution with platform-specific requirements.
245-257: User Field Assignment Test Verification.
The test inTestNewCrontabWithCurrentUsersuccessfully confirms that the new user information is correctly injected into the crontab entries. This is especially important after the recent adjustments concerning user permissions and the handling of the "logged in" state.
310-330: Robust Environment Variable Handling Tests.
The tests that manipulate theNO_CRONTABandCRONTABenvironment variables validate both the loading and saving behaviours of the crontab mechanism. This comprehensive coverage is essential for ensuring that scheduling operations behave as expected in different runtime scenarios.crond/parse_event_test.go (1)
1-2: Appropriate build constraint for non-Windows platforms.The build constraint
//go:build !windowsensures that these tests only run on non-Windows platforms, which is correct as cron is a Unix/Linux concept that doesn't apply to Windows systems.crond/entry_test.go (1)
1-2: Appropriate build constraint for non-Windows platforms.The build constraint
//go:build !windowsensures that these tests only run on non-Windows platforms, which is correct as cron is a Unix/Linux concept that doesn't apply to Windows systems.user/user_systemd.go (2)
1-2: Appropriate build constraint for Linux-specific code.The build constraint
//go:build !windows && !darwinensures this file is only built on Linux systems where systemd is available, which is appropriate for the implementation.
11-14: Function correctly checks for systemd lingering status.This implementation properly checks if a user has lingering enabled in systemd by looking for the existence of the user's file in the systemd linger directory. This supports the PR objective of distinguishing between
useranduser_logged_inpermissions, as lingering allows services to run even when the user is not logged in.schedule/config.go (1)
49-51: Changed default priority from "background" to "standard".The default priority has been changed from "background" to "standard" for scheduled tasks. This change appears intentional but could affect existing users who were relying on the previous default behavior.
Consider documenting this change in release notes to inform users about the change in default behavior.
user/user_windows.go (3)
1-2: Build tag correctly identifies the platformThe build tag ensures this file is only compiled for Windows systems, which is appropriate given the platform-specific implementation.
5-7: Appropriate import for user informationThe code correctly imports only the necessary
os/userpackage for retrieving user information on Windows.
9-23: Windows-specific implementation handles platform differences correctlyThe implementation correctly adapts the
Current()function for Windows by:
- Retrieving the username and home directory using the standard library
- Setting the UID and GID to -1 (since Windows doesn't use the Unix UID/GID concept)
- Setting SudoRoot to false (as Windows doesn't have the sudo concept)
This maintains API compatibility with the non-Windows implementation while accounting for Windows platform differences.
user/user_test.go (4)
1-10: Appropriate imports for testingThe imports include necessary testing packages and the platform detection utility that will be needed for platform-specific assertions.
12-21: Test verifies common properties across platformsThe test correctly checks platform-agnostic properties:
- SudoRoot flag matches the effective user ID
- Username is not empty
- HomeDir matches the result from os.UserHomeDir()
These assertions are valid for all supported platforms.
22-25: Platform-specific assertions for non-Windows systemsThe test intelligently skips UID/GID assertions on Windows, where these values are set to -1. The values 500 and 0 are reasonable thresholds for regular user accounts on Unix-like systems.
26-27: Logging user information aids debuggingLogging the full user struct helps with test debugging and verification.
commands_schedule_test.go (2)
45-45: Added 'user' permission for inline schedule configurationThis addition aligns with the PR objective to properly distinguish between
useranduser_logged_inpermissions in systemd and launchd. The permission is specified at the correct location in the inline configuration.
51-51: Added 'user' permission for structured schedule configurationThis addition complements the inline configuration change above, ensuring both configuration styles support the same permission model. This properly implements the distinction between
useranduser_logged_inpermissions in the structured configuration style.darwin/session_type_test.go (3)
1-2: Build tag correctly identifies the platformThe test file has the appropriate build tag to ensure it's only compiled for Darwin (macOS) systems, which is relevant since the
darwinpackage contains macOS-specific functionality.
5-9: Minimal imports for testingThe imports are minimal and appropriate, only including the testing package and the assertion library.
11-26: Comprehensive test for session type mappingThe test covers all important permission mappings:
- Empty string (default case)
- Invalid permission string
- "user_logged_on" permission
- "user" permission
- "system" permission
This ensures the
NewSessionTypefunction correctly maps all permission types to the appropriate session types, which is essential for the PR objective of distinguishing betweenuseranduser_logged_inpermissions.darwin/process_type_test.go (1)
1-42: Well-structured test case for NewProcessType functionThis is a good test implementation that covers all major cases including background priority, standard priority, and unknown priority scenarios. The test structure with table-driven tests follows Go best practices, making it maintainable and easy to extend with additional test cases if needed.
The test clearly validates the expected behavior of the
NewProcessTypefunction with different inputs and has good error messages that would make debugging easier if tests fail.schedule/config_test.go (4)
39-39: Default schedule priority is now "standard" instead of "background"This change aligns with the update to make "standard" the default priority value. This is consistent with the PR objective to clarify permission handling.
44-46: Updated test case for background priorityThe test is now properly checking for "background" priority handling. This ensures the priority value is correctly preserved when explicitly set to "background".
51-53: Case insensitivity test updated for background priorityGood update to verify that case-insensitive priority values still map to the correct lowercase value, maintaining backward compatibility with existing configurations.
60-60: Default handling for unknown priorities updatedThis change ensures unknown priority values correctly fall back to the new "standard" default, which is consistent with the other test changes.
schedule/job_test.go (9)
8-8: Import of constants package addedGood addition of the constants package import to use the newly defined schedule permission constants instead of hardcoded strings, improving code maintainability.
17-18: Added permission detection and checkingThese new assertions validate that the job creation process properly checks for the required permissions before proceeding, which aligns with the PR objective to improve permission handling.
21-21: Updated to use type-safe permission parameterThe mock expectation has been updated to use a strongly-typed permission enum (
schedule.PermissionUserBackground) instead of a string, which reduces the risk of errors from mistyped permission strings.
27-27: Using permission constant instead of string literalGood practice to use the defined constant instead of a string literal. This ensures consistency and makes it easier to update permission values if needed in the future.
36-37: Permission detection and checking for auto permissionThese expectations verify that auto-permission is properly resolved to the appropriate permission type and checked before job creation, improving permission handling robustness.
53-54: Consistent permission checking across test casesThe same permission detection and validation pattern is applied consistently across all test cases, ensuring comprehensive test coverage of the permission handling logic.
69-70: Permission handling for error case testingGood to see that permission checking is also validated in the error case tests, ensuring that permission checks happen before attempting to create a job that might fail.
73-73: Type-safe permission parameter in error caseConsistent use of the strongly-typed permission enum in the CreateJob mock call, maintaining type safety across all test cases.
79-79: Permission constant in error test caseUsing the constant here maintains consistency with the success test case, making the test more maintainable.
constants/value.go (2)
5-6: New schedule permission constants addedAdded
SchedulePermissionAutoandSchedulePermissionSystemconstants, which aligns with the PR objective to improve permission handling in systemd and launchd. The "auto" permission type likely provides a way to automatically detect the appropriate permission level.
9-12: Clear separation between permission and priority constantsThe added newline helps visually separate the permission constants from the priority constants, improving code readability and organization.
user/user_other.go (1)
1-39: Well-implemented user detection for non-Windows platformsThis implementation correctly handles the case where a user might be running with root privileges via sudo by checking the
SUDO_UIDenvironment variable. It properly populates the User struct with the original user's information rather than returning root user details.examples/dev.yaml (2)
110-112: Good change to list format for source pathsConverting the source from a single string to a list format provides more flexibility and aligns with common YAML best practices for collections of values.
115-117: Updated schedule permission to use new 'user_logged_on' valueThis change properly implements the PR objective by switching from
usertouser_logged_onpermission, addressing the issue whereuserpermission was incorrectly interpreted asuser_logged_inin systemd and launchd.systemd/generate.go (4)
90-90: Appropriate addition of User field to templateInfo structThis change allows the User value to be passed to the systemd unit template.
113-113: Good addition of User field to Config structAdding the User field to the Config struct allows specifying a user for the systemd service, supporting the distinction between user and user_logged_in permissions.
135-149: Improved user handling for systemd servicesThe updated code properly handles the case where a specific user is provided in the config. When a user is specified, it correctly sets up the environment variables to work with that user's home directory.
246-247: Simplified user retrieval in GetUserDirUsing the new
user.Current()function simplifies the code and provides better handling of edge cases like sudo users.crond/crontab.go (1)
176-179: Improved username detection with better sudo handlingSwitching to the custom user package's
Current()function provides better handling of sudo cases by checking for the SUDO_UID environment variable and retrieving the actual username.However, the previous implementation had explicit error handling for the user lookup, while the new implementation does not. Since
user.Current()would still return a User struct with empty fields rather than an error, this is acceptable, but it's worth noting the change in error handling approach.examples/linux.yaml (3)
9-9: Commented configuration options reflect a change in default behaviourI notice that several configuration options are now commented out (
systemd-unit-template,nice, andscheduler). This change suggests a shift in how these settings are managed. Make sure this is documented in the migration guide for users who might rely on these settings.Also applies to: 14-15
104-107: Structured schedule format introduces permission distinctionThe schedule configuration has been updated to use a structured format with explicit permission settings. This supports the PR objective of distinguishing between
useranduser_logged_inpermissions. Thepermission: systemvalue means this backup will run with system privileges.🧰 Tools
🪛 YAMLlint (1.35.1)
[warning] 105-105: wrong indentation: expected 12 but found 10
(indentation)
112-117: New forget section with user_logged_on permissionThis new
forgetsection introduces theuser_logged_onpermission type, which directly addresses the PR objective of clarifying the distinction betweenuseranduser_logged_inpermissions. This is a good addition that enhances the scheduling capabilities for users.darwin/process_type.go (2)
7-12: Appropriate type definition for process classificationThe
ProcessTypestring type with defined constants provides a clean approach for classifying launchd jobs. The constants clearly represent the supported process types that will be used in the launchd configuration.
14-25: Clean implementation of priority mappingThis function properly translates between the application's priority constants and macOS's process types. The implementation is straightforward and handles all expected cases, including the default case where an unknown priority returns an empty string.
darwin/launchd.go (2)
7-82: Well-documented launchd job structureThe
LaunchdJobstruct provides comprehensive support for macOS launchd configuration with clear documentation. The structure accurately reflects the launchd property list format and includes fields needed for the new permission model.
89-99: Proper session type documentation for LimitLoadToSessionTypeThe comments explain the various session types well, which is essential for understanding when jobs will be executed. This directly supports the PR objective of distinguishing between
useranduser_logged_inpermissions by mapping to macOS session types.schedule/handler.go (3)
8-8: Added user package import for permission checkingThe addition of the user package import supports the new permission model by allowing the handler to check user-specific permissions.
18-20: Updated method signatures to use Permission typeThe
CreateJobandRemoveJobmethods now use thePermissiontype instead of a string, which enforces type safety and better matches the PR objective of clarifying permission handling.
23-28: New permission detection and verification methodsThe addition of
DetectSchedulePermissionandCheckPermissionmethods enhances the interface with explicit permission handling capabilities. These methods are essential for the PR objective of distinguishing between different user permission types.darwin/calendar_interval.go (3)
3-3: Package name has been changed to 'darwin'The package has been moved from 'schedule' to 'darwin', which accurately reflects the Darwin-specific nature of this code (as indicated by the build tag). This change improves the package organisation.
67-73: Function now exported with capital letterThe function
getCalendarIntervalsFromScheduleshas been renamed toGetCalendarIntervalsFromSchedulesto make it accessible outside the package. This is part of the permission system refactoring and allows other packages to use this functionality directly.
119-140: Function now exported with capital letterThe function
parseCalendarIntervalshas been renamed toParseCalendarIntervalsto make it accessible outside the package. This allows other components to convert calendar intervals into string representations without relying on package-private functions.darwin/calendar_interval_test.go (2)
1-56: Well-structured tests for ParseCalendarIntervalsThe test cases provide good coverage for the
ParseCalendarIntervalsfunction, including single interval, multiple intervals, and empty intervals. This will ensure the function works correctly across different scenarios.
58-111: Comprehensive test for GetCalendarIntervalsFromScheduleTreeThese test cases verify that the function correctly converts various schedule strings into calendar intervals. The tests cover simple cases as well as more complex scenarios (like weekday ranges and time ranges), which is good for ensuring the robustness of the implementation.
schedule_jobs_test.go (6)
9-9: Added import for constants packageThe constants package is now imported to access the schedule permission constants like
constants.SchedulePermissionUser. This is part of the switch from string-based permissions to type-based permissions.
39-40: Updated mock expectations to use Permission typeThe mock expectations now use
schedule.PermissionUserBackgroundinstead of string literals, and call the newDetectSchedulePermissionandCheckPermissionmethods. This aligns with the new type-safe permission system.Also applies to: 65-66, 97-98, 117-118, 137-138, 153-154, 169-170
46-47: Updated RemoveJob and CreateJob calls to use Permission typeThe calls to
RemoveJobandCreateJobhave been updated to use the typedschedule.Permissionparameter instead of strings, improving type safety in the scheduling system.Also applies to: 72-73, 99-100, 139-140, 155-156, 171-172
226-227: Updated test struct to use Permission typeThe test case struct now uses
schedule.Permissioninstead ofstringfor the permission field, and test data usesconstants.SchedulePermissionUserinstead of string literals. This makes the tests consistent with the new type-safe permission system.Also applies to: 233-234, 243-244, 251-252, 254-255, 264-265, 268-269
281-283: Added permission detection and checking to mocksThe test now includes expectations for the new permission detection and checking methods, ensuring that the updated permission workflow is properly tested.
Also applies to: 310-313
400-401: Updated permission in test configurationThe permission in the test configuration now uses
constants.SchedulePermissionUserinstead of a string literal, maintaining consistency with the new permission system.schedule/job.go (7)
5-8: Added additional importsThe code now imports "fmt" for improved error formatting and "github.com/creativeprojects/clog" for logging warnings when permissions are guessed. This enhances error reporting and user feedback.
38-40: Updated Accessible method to use new permission APIThe
Accessiblemethod now uses the handler'sDetectSchedulePermissionandCheckPermissionmethods instead of standalone functions. This encapsulates permission handling within the handler interface, making it easier to extend or modify permission logic.
48-50: Added permission detection and checking in Create methodThe
Createmethod now gets the schedule permission using the newgetSchedulePermissionhelper method and checks it using the handler'sCheckPermissionmethod. This improves the handling of permissions and provides better feedback to users.
71-79: Improved permission handling in Remove methodThe
Removemethod has been updated to use the handler's permission detection and checking methods. It now handles the case where a job is marked for removal only differently, making a "silent call" for possibly non-existent jobs. This provides more robust permission handling.
96-96: Enhanced error messagesError messages now use
fmt.Errorfwith%wverb to wrap the original error, providing more context about what operation failed. This makes debugging and error handling easier for developers.Also applies to: 100-100
105-114: Added getSchedulePermission helper methodThis new method encapsulates the logic for determining the appropriate permission, either from configuration or by detecting it. It also logs a warning if the permission had to be guessed, improving user feedback about permission-related issues.
116-120: Added permissionError helper methodThis method creates a standardised error message for permission-related problems, improving user experience by providing clear guidance (to use sudo for system-level jobs). The comment also notes that this isn't used on Windows, which is helpful context for platform-specific behaviour.
darwin/session_type.go (7)
1-2: Looks good – standard Go build tag.
No issues here.
3-4: No issue with package declaration.
All standard for a Go file.
5-6: Import is appropriate.
Nothing to flag with this import statement.
7-8: Type definition is clear and unambiguous.
DefiningSessionTypeas a string is a standard way to store enumerations in Go. No issues here.
9-15: String constants for session types are well-defined.
These named constants provide clarity for different Darwin session types. Everything appears aligned with typical usage.
17-32: Verify the mapping of permissions to session types.
SchedulePermissionUseris mapped toSessionTypeBackground, whereasSchedulePermissionUserLoggedOn/SchedulePermissionUserLoggedInmap toSessionTypeGUI. Confirm this is correct for Darwin, especially if you need a separate session type for logged on vs. logged in scenarios.
34-45: Confirm reverse mapping to 'user_logged_on' by default.
SessionTypeGUIandSessionTypeDefaultboth returnSchedulePermissionUserLoggedOn, with no direct reference touser_logged_inin the reverse mapping. Verify that intentionally discardinguser_logged_inis acceptable, or consider differentiating them.schedule/permission.go (4)
7-7: Integer-based approach is more robust.
Switching from a string-based to an integer-basedPermissionlikely improves type safety and clarity.
10-13: Check for missing 'PermissionUserLoggedIn'.
Currently, the code definesPermissionUserLoggedOnbut notPermissionUserLoggedIn. Please verify you do not need a separate constant for 'user_logged_in'.
16-30: Mapping user_logged_in and user_logged_on to the same permission.
PermissionFromConfigmergesuser_logged_inwithuser_logged_on->PermissionUserLoggedOn. Confirm this is intentional.
32-47: Defaulting unhandled permissions to 'auto'.
The function returns'auto'for unrecognised values and does not differentiate betweenuser_logged_inanduser_logged_onin reverse. Confirm that merging them aligns with your design requirements.schedule/mocks/Handler.go (8)
10-11: Importing user package is consistent with new signature requirements.
This is necessary for the newCheckPermissionmethod.
27-43: New CheckPermission method aligns with updated interface.
Implementation correctly matches the interface definition for permission checking. No issues noted.
45-73: Mock call types for CheckPermission.
These generated mocks handle the new method. Everything looks correct.
107-133: Updated CreateJob signature uses schedule.Permission.
This matches the shift to integer-based permissions. The mock behaviour is consistent.
137-152: Running the CreateJob mock call.
Accepts the newschedule.Permissiontype without issue. Approving the changes.
154-180: DetectSchedulePermission mock is consistent.
Auto-generated code integrates the new method for permission detection. No concerns.
182-208: Handling mock calls for DetectSchedulePermission.
This properly reflects the new method signature returning(schedule.Permission, bool).
453-499: RemoveJob signature updated to schedule.Permission.
All references correctly changed. Auto-generated code matches the interface updates..github/workflows/doc.yml (1)
58-58: Improved regex pattern for link exclusions.The changes to the exclusion pattern improve the regex by properly escaping dots in domain names and adding
0-18to the excluded patterns. This ensures more precise matching of domains and prevents false positives..github/workflows/release-doc.yml (1)
52-52: Improved regex pattern for link exclusions.The changes to the exclusion pattern improve the regex by properly escaping dots in domain names and adding
0-18to the excluded patterns. This ensures more precise matching of domains and prevents false positives.systemd/read.go (1)
56-56: Good addition of User field to the Config struct.This change aligns with the PR objectives to better handle user permissions in systemd. Adding the User field allows the configuration to capture the user under which the service should run, which is essential for properly distinguishing between
useranduser_logged_inpermissions.examples/sample.service (2)
4-5: Proper conditional templating for network dependency.The addition of this conditional block provides better configurability by including the
After=network-online.targetdirective only when the network dependency is specifically required. This improves service startup behavior by ensuring network dependency is only declared when needed.
17-19: User context support added.This change enables specifying a user context for the service, which directly addresses the PR objective of disambiguating between
useranduser_logged_inpermissions in systemd. The implementation correctly uses a conditional template to only include the User directive when specified.systemd/generate_test.go (1)
563-596: Excellent test coverage for new User field functionality.This test comprehensively validates the new User field implementation by:
- Setting up a test environment
- Generating a systemd service with a specified user
- Verifying the generated service file contains the correct User directive
- Confirming environment variables are correctly set
The test ensures the template substitution works correctly, which is crucial for the proper functioning of the User permission in systemd services.
schedule/schedules.go (2)
51-54: Improved handling of empty schedules.This addition properly handles the case when a schedule has no future occurrences by displaying a clear "Never" message and skipping the irrelevant time calculations. This prevents confusing or misleading output for schedules that will never execute.
68-68: Enhanced command path reliability.Using the full path
/usr/bin/systemd-analyzeinstead of relying on PATH resolution improves reliability across different environments and execution contexts. This is particularly important when running under different user contexts as introduced by this PR.schedule_jobs.go (1)
127-127: Fixed flow control in error handling.Adding this
continuestatement prevents misleading log messages by skipping the success message after an error has occurred. This ensures the logs accurately reflect the actual state of operations and avoids confusion for users and administrators troubleshooting schedule issues.docs/content/schedules/cron.md (1)
1-190: Documentation looks comprehensive and well-structured.This new documentation file provides clear instructions for using crond-compatible schedulers on non-Windows systems. The examples in multiple configuration formats (TOML, YAML, HCL, JSON) are particularly helpful. The warning about Windows support removal is appropriately highlighted.
systemd/read_test.go (2)
111-124: Test case added for User field verification.The new test case correctly validates the handling of the User field in systemd configurations, which aligns with the PR objective of improving user permission handling in systemd.
154-154: Properly propagating User field in expected config.This line ensures the User field from the test configuration is properly expected in the verification, completing the test coverage for this new property.
Makefile (2)
197-197: Improved tmpfs mount with proper user permissions.Adding the current user and group IDs to the mount command ensures the temporary filesystem is accessible to the current user without requiring root privileges for subsequent operations.
301-301: Fixed regex pattern in link checker.The modification properly escapes dots in domain names and adds "0-18" to the exclusion pattern, improving the reliability of the link checking process.
schedule/handler_windows_test.go (2)
11-15: Windows crond support removal correctly documented.This commented-out test code includes a clear explanation that Windows support for crond has been removed due to it being broken, which aligns with the documentation in
cron.md.
22-47: Good test coverage for permission detection in TaskScheduler.This new test function thoroughly tests the
DetectSchedulePermissionmethod for the Windows TaskScheduler handler. It covers various input scenarios including empty strings, known permissions, and even accounts for the "user_logged_in" vs "user_logged_on" typo mentioned in line 35.The test properly verifies:
- Expected permission string output
- Safety status of each conversion
- Specific handling of "user_logged_in" being mapped to "user_logged_on"
The test structure using table-driven tests and parallel execution is well-implemented.
schedule/handler_crond_test.go (5)
1-2: Build constraint properly restricts test executionThe build constraint ensures these tests only run on non-Windows platforms, which is appropriate for crond functionality testing as cron is a Unix/Linux-specific service.
35-35: Appropriately added permission field to test configurationsAdding explicit permission values to the test configurations ensures proper testing of the new permission handling system, distinguishing between "user" and "system" permissions.
Also applies to: 50-50
69-69: Correctly updated permission handling in API callsThe switch from passing raw permission strings to using the structured
PermissionFromConfigfunction improves type safety and aligns with the new permission system implementation.Also applies to: 80-80
89-114: Comprehensive permission detection testingThe new test function thoroughly validates the permission detection system with various input values, including:
- Default values for empty or invalid inputs
- Correct mapping of standard permission strings
- Support for the
user_logged_inalias foruser_logged_on(handling potential typos)- Safety flag validation for each permission type
This ensures the permission detection system works reliably across different inputs.
116-176: Thorough permission checking test casesThe test function properly validates that:
- User-level permissions work correctly for non-root users
- System permissions require root access
- Undefined permissions default to requiring root access
- All permission types are checked with both root and non-root users
This ensures the permission checking system properly enforces security constraints.
docs/content/schedules/systemd.md (8)
8-8: Improved introduction clarityThe rephrased introduction provides a clearer, more concise explanation of systemd and resticprofile's interaction with it.
39-52: Excellent new section on priority and CPU schedulingThe new section provides valuable information about resticprofile's ability to configure CPU scheduling parameters. The table clearly explains the mapping between systemd options and resticprofile settings, and the note about potential issues with the idle policy is important for users to understand.
55-66: Clear explanation of the updated permission systemThe expanded permission section excellently documents the previous behaviour issue and the new, corrected permission system. The table format makes it easy to understand the differences between permission types and how lingering affects each one. This directly addresses the PR objective of clarifying the distinction between
useranduser_logged_inpermissions.
71-71: Improved explanation of network-online optionThe rephrased description provides a clearer explanation of how the network-online option works and what it does in the systemd configuration.
76-76: Clearer explanation of drop-in filesThe more direct phrasing ("You can" instead of "It is possible to") makes the text more engaging and easier to understand.
165-165: Better explanation of systemd credentialsThe updated explanation clarifies the purpose of the credentials feature and how it relates to TPM-backed encryption.
180-184: Improved explanation of custom templatesThe updated text more clearly explains the purpose and benefit of custom templates.
231-231: More helpful recommendation for template customizationThe suggestion to use the default templates as a starting point is helpful for users who want to create custom templates.
schedule/handler_systemd_test.go (6)
11-12: Required imports for new test functionalityThe added imports support the new test functions that verify permission handling in systemd context.
21-21: Corrected permission default for systemd testsChanging from
SchedulePermissionUsertoSchedulePermissionUserLoggedOnproperly reflects the intended behavior for systemd user units as described in the PR objective.
62-62: Updated API calls to use structured permission typeThe switch from passing raw permission strings to using the structured
PermissionFromConfigfunction improves type safety and aligns with the new permission system implementation.Also applies to: 66-66, 90-90
99-124: Comprehensive systemd permission detection testingThis test function thoroughly validates the systemd-specific permission detection with various input values, including default behaviors and support for aliases. The test ensures that the systemd permission detection correctly handles all permission types and edge cases.
125-164: Test validates correct mapping from systemd config to permissionsThis test function ensures that the systemd configuration correctly maps to the appropriate permission strings based on the unit type and user configuration. It covers all key scenarios:
- System units with user (maps to user permission)
- System units without user (maps to system permission)
- User units (maps to user_logged_on permission)
This helps validate that the systemd configuration correctly implements the permission model.
165-230: Comprehensive testing of permission to systemd type mappingThis test function thoroughly checks the mapping from permission types to systemd unit types and user settings for both root and non-root users. The tests ensure that:
- System permissions correctly map to system units
- User background permissions correctly map to system units with user field
- User logged on permissions correctly map to user units
- Default behaviors differ appropriately based on whether the user is root
This comprehensive testing ensures the permission system works correctly with systemd.
docs/content/schedules/configuration.md (6)
7-7: Improved introduction clarityThe rephrased introduction provides a clearer, more concise description of the schedule configuration parameters.
74-82: Clear differentiation between permission typesThe updated permission descriptions clearly explain the differences between:
system: For accessing protected filesuser: Now explicitly states it runs even when user is not logged onuser_logged_on: Explicitly notes it's for logged-on users only and not for crondThis directly addresses the PR objective of clarifying the confusion between
useranduser_logged_inpermissions.🧰 Tools
🪛 LanguageTool
[uncategorized] ~76-~76: Loose punctuation mark.
Context: ...user, oruser_logged_on: *system: Access system or protected files. Run r...(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~78-~78: Loose punctuation mark.
Context: ...levated permissions if needed. *user: Run the backup using current user permi...(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~80-~80: Loose punctuation mark.
Context: ...password on Windows. *user_logged_on: Not for crond - Provides the same p...(UNLIKELY_OPENING_PUNCTUATION)
84-92: Better instructions for changing permissionsThe reorganized section provides clearer step-by-step instructions for changing permissions, emphasizing the need to unschedule first. This helps prevent configuration errors when users modify permissions.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
90-90: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
91-91: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
92-92: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
97-100: Improved explanation of lock modesThe clarified descriptions of lock modes, particularly for the
defaultmode and its relationship withschedule-lock-wait, make it easier for users to understand the locking behavior.🧰 Tools
🪛 LanguageTool
[uncategorized] ~99-~99: Loose punctuation mark.
Context: ...-waitis "0" or not specified. -fail`: Any lock failure immediately aborts the...(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~100-~100: Loose punctuation mark.
Context: ...ediately aborts the schedule. -ignore: Skips resticprofile locks. Restic locks...(UNLIKELY_OPENING_PUNCTUATION)
🪛 markdownlint-cli2 (0.17.2)
98-98: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
99-99: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
100-100: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
109-113: Clearer explanation of log optionsThe updated explanations for log redirection options more clearly describe how to redirect output to files or syslog servers, and what happens if the syslog server is unavailable.
🧰 Tools
🪛 LanguageTool
[style] ~109-~109: To form a complete sentence, be sure to include a subject.
Context: ...lt. ### schedule-logschedule-log` can be used in two ways: - Redirect all out...(MISSING_IT_THERE)
🪛 markdownlint-cli2 (0.17.2)
110-110: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
111-111: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
118-122: More concise priority explanationThe simplified explanation of priority options removes unnecessary qualifiers while maintaining essential information, making it easier for users to understand.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~120-~120: Loose punctuation mark.
Context: ...s unnoticed while you work. -standard: The process gets the same priority as o...(UNLIKELY_OPENING_PUNCTUATION)
🪛 markdownlint-cli2 (0.17.2)
119-119: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
120-120: Unordered list style
Expected: asterisk; Actual: dash(MD004, ul-style)
docs/content/schedules/launchd.md (10)
2-2: No issues with the updated title.
6-6: Appears clear and correct.
8-8: No concerns regarding the new section.
12-12: Clear explanation of required permissions.
14-14: No issues. Manually starting a profile is explained well.
17-17: No concerns with the example command.
20-20: No issues. The note about macOS limitations is correct.
22-22: New heading is clear and well structured.
24-24: Good explanation on creating a launchd daemon.
26-26: No further concerns here.docs/content/schedules/commands.md (17)
8-8: The list of commands is clear.
13-13: Explanation of operating scope is concise.
16-16: Historical note is informative.
17-18: Group scheduling details are clearly described.
29-29: Providing clarity on schedule independence is beneficial.
33-33: No issues installing all schedules in the selected profiles.
35-35: Note regarding systemd timer start is helpful.
37-40: Clear explanation for user versus privileged modes with--all.
42-42: Advice about unscheduling prior to v0.30.0 is well-documented.
47-47: Removing schedules from selected profile(s) is explained well.
49-49: Behaviour before version v0.30.0 is clearly clarified.
52-54: Enhanced clarity on how unschedule handles deleted or renamed profiles.
58-60: Status command usage and OS dependency are correctly stated.
65-65: Explanation of the internal invocation is concise.
67-67: Guidance for manual scheduling is correct.
69-69: Single argument format for run-schedule is well documented.
77-77: Clarification about the profile name usage is correct.schedule/handler_windows.go (4)
50-50: Refactoring CreateJob to accept typed permission is good.
53-55: Correctly mapping PermissionUserBackground and PermissionUserLoggedOn to schtasks.
120-131: Logic for detecting schedule permission on Windows is straightforward.
Always returningtruefor the second value is consistent with the simplified permission approach on Windows.
133-136: Always returning true in CheckPermission is intentional for Windows.schedule/handler_crond.go (12)
1-2: Build tags are correctly specified for non-Windows builds.
6-6: Importing os is necessary for EUID checks.
9-9: Using clog for debug logs is appropriate.
15-15: Importing user is consistent with permission checks.
45-45: Debug message for using a custom crontab file is welcome.
48-48: Debug message for standard cron scheduler is correct.
76-76: Accepting typed permission for CreateJob aligns with the new design.
88-92: Assigning 'root' if permission is system, otherwise using h.config.Username.
This is coherent with the intended behaviour.
106-106: RemoveJob also receives typed permission, maintaining consistency.
150-153: Translating cron entry user into system or user permission.
This logic is sound, though it lumps both user background and user logged on underSchedulePermissionUser.
177-195: DetectSchedulePermission
Returns well-defined permissions for system/user modes, otherwise guesses based on EUID. The logic and safety flag usage are correct here.
198-212: CheckPermission
Restricts system scheduling to users with sudo or UID zero, otherwise returns true for user modes. This is well implemented.docs/content/schedules/_index.md (10)
9-9: No issues with the new “Scheduler” heading.
11-16: Clear introduction of scheduling methods.
No concerns found—this section succinctly explains each scheduler.
20-20: Reference to global configuration.
It’s sensible to retain a mention of the global section if users still rely on it. Ensure that referencing the “global” section for scheduler configurations remains valid with your new approach.
22-28: Profile-specific scheduling explanation looks good.
The outlined sections to schedule (backup, check, forget, prune, copy) are well listed.
29-30: Deprecation notice.
This section is clearly labelled and clarifies the new usage offorgetoverretention.
32-32: Documentation for retention usage.
This clarifies that retention shouldn’t be scheduled independently. Well stated.
38-44: TOML snippet guidance.
The example properly illustrates the deprecatedretentionschedule and the recommendedforgetapproach.
53-60: YAML snippet guidance.
No issues here—this snippet aligns with the TOML example and clarifies the deprecation.
67-76: HCL snippet guidance.
The transition to scheduling theforgetsection is also consistent here.
85-88: JSON snippet guidance.
Good omission of the deprecated section, highlighting theforgetapproach instead.schedule/handler_darwin_test.go (12)
8-8: New import for “maps”.
No issues identified—this library is standard in newer Go versions.
10-11: Imports for “slices” and “strings”.
These imports look fine and align with standard library usage.
16-16: Importing the “darwin” package.
No immediate concerns; this import seems to integrate well with the existing code.
79-82: Creating a new LaunchdJob for user background tests.
Implementation is straightforward; everything here appears correct.
93-96: Creating a new LaunchdJob for system tests.
Logic reflects the intended System permission path. No concerns.
133-133: Switch to constants.SchedulePermissionUserLoggedOn.
Ensures the job is run under the logged-on user session. This aligns with the new approach to user scheduling.
161-161: PermissionFromConfig usage in test.
This correctly verifies that the test uses the updated permission model.
170-170: Blank line change.
No functional impact.
257-265: assertMapHasKeys utility function.
This is a neat helper to confirm key presence. No issues here.
267-282: TestIsServiceRegistered.
Checks for well-known system service. Looks good; no issues.
284-294: TestParsePrintSystemService.
Validates system service output format from launchctl. Straightforward.
295-320: TestDetectPermissionLaunchd.
Thorough coverage of user permission variants, including typed mistakes. Excellent approach.schedule/handler_systemd.go (11)
42-43: Fixed binary paths for systemctl and journalctl.
Be aware some distributions may place these binaries elsewhere (e.g.,/binor/usr/local/bin). Consider making these paths configurable.
107-108: CreateJob signature uses Permission.
Shifting from string to typed Permission improves code clarity.
111-111: New error for after-network-online under user_logged_on.
This highlights correct usage. The restriction aligns well with local user sessions.
132-132: Specifying User in systemd.Config.
This ensures the correct user is set within the generated service.
167-169: RemoveJob signature and usage of permissionToSystemd.
The typed permission approach ensures consistent and explicit scheduling behaviour.
229-229: Using DetectSchedulePermission in DisplayJobStatus.
Ensures a final check of the permission type for system vs. user.
231-231: Condition for system or user background.
Applying SystemUnit to both system and user background is consistent with your design, though it may surprise some users.
266-284: DetectSchedulePermission implementation.
Logic to determine final permission is clear and straightforward.
286-301: CheckPermission function.
The approach for verifying user or system permission looks correct.
307-324: permissionToSystemd function.
Mapping PermissionUserBackground to systemd.SystemUnit might be unexpected. Verify this is the intended design.
431-437: getUserFlags function.
Neatly handles the difference between sudo sessions and normal user sessions by adding user flags.schedule/handler_darwin.go (19)
6-6: Consolidate and verify imports.
Adding"bytes","github.com/creativeprojects/resticprofile/darwin", and"github.com/creativeprojects/resticprofile/user"appears correct. Ensure that all newly introduced imports are being utilised as intended and that thebytespackage usage remains valid throughout the code.Also applies to: 17-17, 19-19
30-36: Constants appear consistent.
Renaming or introducinglaunchdBootstrapandlaunchdBootoutaligns with current launchctl nomenclature. Also, havingGlobalAgentPathandGlobalDaemonsdefined here makes it explicit. If these constants are reused extensively, consider consolidating them in a single constants file for easier maintenance.
42-42: Refined error code and print keys.
DefininglaunchctlServiceNotFound = 113and thelaunchctlPrintKeysarray helps keep errors descriptive. Good approach to unify known error codes and consistent debug output.Also applies to: 45-45
54-54: Confirm launchctl presence at runtime.
UsinglookupBinary("launchd", launchctlBin)ensureslaunchdis accessible. This is an effective defensive check.
81-91: Pre-emptively removing existing jobs.
The new function signature now uses thePermissiontype, which improves type safety. Checking if the service is already registered and removing it first is sensible, but it may override partial states if users needed them. Confirm that automatic removal is acceptable in all cases.
100-100: Registering the job with bootstrap.
CallinglaunchctlCommand(launchdBootstrap, domainTarget(permission), filename)follows the new naming convention. The steps for job creation are easy to follow.
112-112: Updated function signature for RemoveJob.
Switching from a string-based permission toPermissionensures consistency with other scheduling handlers.
123-123: Loading the correct bootout command.
UsinglaunchctlCommand(launchdBootout, domainTarget(permission)+"/"+name)to unload the job is consistent with the updated domain targeting approach.
139-161: Enhanced status display logic.
The newly introducedDetectSchedulePermissioncall and subsequent domain-targetedlaunchctl printinvocation help clarify which domain the status belongs to. Parsing and displaying the status viaparsePrintStatusandpresentStatusis straightforward and user-friendly.
184-216: Consistent LaunchdJob construction.
Returning a*darwin.LaunchdJobneatly decouples the launchd logic from local structs. The inclusion ofWorkingDirectory, environment maps, and scheduling intervals looks consistent. Ensure--no-priodoes not conflict if the user includes it in their own arguments.
234-236: Synchronising in-memory permission.
Filling injob.Permissionif it was initially empty aligns with the final resolved permission, keeping the configuration consistent.
263-279: New CheckPermission function.
Requiring sudo or root privileges for system-level tasks while allowing standard users for user-level tasks is logically sound. This approach closes potential loopholes for unauthorised schedule modifications.
361-361: Reading plist into the new struct.
Decoding directly intodarwin.LaunchdJobmatches the updated references. The steps are clear, and error handling is straightforward.Also applies to: 369-369
385-386: Refined system vs. user agent path resolution.
Conditionally returning Daemons vs. Agents paths is coherent with system-level vs. user-level scheduling.
396-409: domainTarget handles custom domain strings.
Having a switch onPermissionto produce"system","gui/<uid>", or"user/<uid>"effectively ensures correct domain usage for each scheduling scenario. Returning an empty string for an unknown permission type is acceptable for now, but consider raising an error if misuse is likely.
411-414: Debug logging for launchctl invocation.
Printing the command viaclog.Debugfis good for troubleshooting. A context-based approach could be used in future for cancellations but is not strictly necessary here.
416-436: Parsing output from launchctl print.
Splitting lines on'='and skipping lines containing'=>'is a neat approach. Ensure edge cases like lines containing extra whitespace or unrecognised tokens are handled gently.
438-453: Mapping 'domain' key to 'permission'.
Transforming domain references to user-friendly permission labels clarifies output. Appending " (*)" to "runs" or "last exit code" is a helpful visual cue.
455-464: Service registration query.
Executing"launchctl print"and checking the exit code forlaunchctlServiceNotFoundis an efficient way to verify job presence. This approach is consistent with the rest of the domain-based logic.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
schedule/handler_darwin_test.go (1)
172-256: Comprehensive test for launchctl output parsing.This test thoroughly verifies the parsing of launchctl output with a detailed fixture. While the test is effective, the large fixture might make maintenance more challenging.
Consider moving the large fixture to a separate variable or file to improve readability:
-const launchctlOutput = `user/503/local.resticprofile.self.check = { - active count = 0 - path = /Users/cp/Library/LaunchAgents/local.resticprofile.self.check.agent.plist +// Define the launchctl output fixture at the package level or in a separate test helper file +var launchctlOutputFixture = `user/503/local.resticprofile.self.check = { + active count = 0 + path = /Users/cp/Library/LaunchAgents/local.resticprofile.self.check.agent.plist
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
schedule/handler_darwin_test.go(7 hunks)schedule/schedules.go(1 hunks)schedule/schedules_test.go(2 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
schedule/handler_darwin_test.go (7)
calendar/event.go (2)
NewEvent(27-42)Event(15-24)darwin/calendar_interval.go (1)
GetCalendarIntervalsFromSchedules(67-73)darwin/launchd.go (1)
LaunchdJob(7-100)schedule/permission.go (5)
PermissionUserBackground(12-12)PermissionSystem(11-11)Permission(7-7)PermissionFromConfig(16-30)PermissionUserLoggedOn(13-13)constants/value.go (1)
SchedulePermissionUserLoggedOn(8-8)constants/global.go (1)
SchedulerLaunchd(11-11)schedule/handler_darwin.go (1)
HandlerLaunchd(47-50)
🔇 Additional comments (16)
schedule/schedules.go (1)
50-53: Enhanced handling of schedules that will never occurThis is a good addition that handles the case when a schedule has no future occurrences. Instead of displaying potentially confusing time information for a zero time, the function now clearly communicates this state to the user and skips irrelevant time-related output.
This change aligns with the PR objectives to improve permission handling in systemd and launchd contexts, where scheduling is permission-dependent.
schedule/schedules_test.go (2)
50-61: Test added for schedules that will never runGood test implementation for the new zero-time handling feature. Using a date from the past (2020-01-01) ensures that the test verifies the "Next elapse: never" condition properly. This test effectively covers the new functionality in the
displayParsedSchedulesfunction.
63-76: Renamed/restructured test maintains previous coverageGood job maintaining test coverage for the index and total display functionality. This test effectively verifies that multiple schedules display their position index correctly (e.g., "schedule 1/3").
schedule/handler_darwin_test.go (13)
8-11: Good use of standard library packages.The addition of
maps,slices, andstringspackages provides access to modern Go utilities for map operations and string manipulations, which are used effectively in the new test functions.
16-17: Well-structured import additions.Adding the
darwinanduserpackages aligns with the PR objectives of improving permission handling, specifically for user-related scheduling.
29-38: Improved test structure with proper abstractions.The test now uses structured
calendar.NewEventanddarwin.GetCalendarIntervalsFromSchedulesinstead of manual setup. This approach leverages the proper abstractions and makes the test more maintainable.The expected output format has been correctly updated to reflect the array structure in the plist XML.
80-83: Good transition to type-safe permissions.Changing from a generic
LaunchdJobtodarwin.LaunchdJoband using the type-safePermissionUserBackgroundinstead of string-based permissions improves code safety and prevents errors.
94-97: Consistent permission type usage.Similar to the user plist test, this uses the typed
PermissionSystemwhich provides consistency in permission handling across the codebase.
134-134: Correct permission constant usage.Changed from
SchedulePermissionSystemtoSchedulePermissionUserLoggedOn, which aligns with the PR objective of clarifying and correctly interpreting user permissions.
162-162: Enhanced permission handling with conversion function.Using
PermissionFromConfigto convert from string permissions in the config to typed permissions is a good practice that centralises the conversion logic and makes the code more robust.
258-266: Well-crafted helper function for map validation.The
assertMapHasKeysfunction provides a clean way to verify that a map contains expected keys, with good error reporting that shows available keys. The use ofslices.Collectandmaps.Keysdemonstrates good use of Go 1.21+ features.
268-283: Good positive and negative test cases for service registration.This test verifies both a non-existent service and a system service expected to exist, covering both success and failure scenarios.
296-321: Comprehensive permission detection testing.This test covers various permission configurations, including the special case of handling the typo 'user_logged_in' as 'user_logged_on', which aligns perfectly with the PR objectives of clarifying permission handling.
323-345: Thorough status presentation testing.The test cases cover various combinations of status keys and values, ensuring proper formatting for display. This improves the user experience when viewing service status.
346-366: Robust domain target generation test.This test verifies the correct domain target generation based on permission types, properly accounting for the current user's UID. The test cases include all relevant permission types, ensuring comprehensive coverage.
285-294:Details
❓ Verification inconclusive
Useful integration test for system service parsing.
This test helps detect changes in the launchctl output format by testing against a real system service. The comment clearly explains the test's purpose.
Since this test depends on the existence of the system service
com.apple.fseventsd, it might fail in some environments. Verify this service exists across macOS versions:
🏁 Script executed:
#!/bin/bash # Check if com.apple.fseventsd exists in different macOS versions launchctl list | grep com.apple.fseventsd || echo "com.apple.fseventsd not found"Length of output: 212
Integration Test Environment Concern
This integration test is designed to monitor changes in the output format of the
launchctlcommand for thecom.apple.fseventsdservice. However, as verified by the script execution, thelaunchctlcommand was not found in the current environment (it returned "com.apple.fseventsd not found"). This indicates that the test may produce false negatives in environments that are not running macOS.
- Location:
schedule/handler_darwin_test.go, Lines 285-294.- Action: Please ensure that this test is executed on a supported macOS system. Alternatively, consider adding a conditional check or skip logic to bypass the test in non-macOS environments.
Implementation of
useranduser_logged_inforsystemdandlaunchdThis fixes a long standing issue where
userpermission was in realityuser_logged_inwhen usingsystemdandlaunchdFixes #331